package com.link.base.base.accnt.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.link.base.base.accnt.model.*;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.accnt.service.ApiAccntService;
import com.link.base.base.accnt.service.ApiStoreService;
import com.link.base.base.cmqres.model.CmqRes;
import com.link.base.base.cmqres.service.CmqResService;
import com.link.base.base.fund.service.DealerAccountService;
import com.link.base.base.invloc.service.InvlocService;
import com.link.base.base.mpconfig.model.Mp;
import com.link.base.base.mpconfig.service.MpService;
import com.link.base.base.order.model.SaleOrder;
import com.link.base.base.order.service.SaleOrderService;
import com.link.base.base.orgnization.service.OrgnizationService;
import com.link.base.base.reception.model.Reception;
import com.link.base.base.reception.service.ReceptionService;
import com.link.base.basic.model.ListOfValue;
import com.link.base.basic.service.BasicCommonService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.mq.util.MqUtil;
import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>客户列表Controller</p>
 * <p>Description</p>
 * <p>Company</p>
 *
 * @author yrf
 * @date 2016年7月11日  下午4:40:56
 */

@Controller
@RequestMapping("/link/accnt")
public class AccountController extends BasicController<Account> {

    @Resource
    private AccountService accountService;
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private CmqResService cmqResService;
    @Resource
    private DealerAccountService dealerAccountService;
    @Resource
    private InvlocService invlocService;
    @Resource
    private BasicCommonService basicCommonService;
    @Resource
    private ApiAccntService apiAccntService;
    @Resource
    private ApiStoreService apiStoreService;
    @Resource
    private OrgnizationService orgnizationService;
    @Resource
    private ReceptionService receptionService;
    @Resource
    private SaleOrderService saleOrderService;
    @Resource
    private MpService mpService;

    /**
     * id异常信息常量
     */
    private String exceptionIdInfo = "客户id不能为空！";

    /**
     * 异常信息常量
     */
    private String exceptionFailInfo = "客户升级组织失败";

    /**
     * 按照List中的某个int类型的属性进行排序 (按照省份客户数排序)
     *
     * @param list
     */

    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void sortIntMethod(List list) {
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Account s1 = (Account) o1;
                Account s2 = (Account) o2;
                if (s1.getTotal() < s2.getTotal()) {
                    return 1;
                } else if (s1.getTotal().equals(s2.getTotal())) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
    }

    @Override
    public BasicService<Account> getBasicService() throws Exception {
        return accountService;
    }

    public void beforUpsert(Account entity, HttpServletRequest request) throws Exception {
        // 如果电汇+现金，则电汇承兑比例不能为空
        if ("WiretransferAndCurrency".equals(entity.getClearingForm())) {
            if (null == entity.getClearingFormRatio()) {
                throw new RuntimeException("电汇/承兑比例不能为空!");
            }
        } else {
            entity.setClearingFormRatio(null);
        }
    }

    /**
     * 客户提交
     *
     * @author yangxiaolin
     * @date 2020/10/29
     */
    @RequestMapping(value = "/accountSubmit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> accountSubmit(@JsonParam Account entity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            accountService.accountSubmit(entity);
            result.put("newRow",entity);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新客户编码及状态
     *
     * @author yangxiaolin
     * @date 2020/10/29
     */
    @RequestMapping(value = "/updateAcctCode", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateAcctCode(@JsonParam Account entity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            accountService.updateAcctCode(entity);
            result.put("newRow",entity);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 客户层级
     *
     * @author yangxiaolin
     * @date 2020/12/12
     */
    @RequestMapping(value = "/accountLevelReport", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> accountLevelReport(@JsonParam Account entity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<Account> list = accountService.accountLevelReport(entity);
            result.put("result",list);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 客户层级查看接口
     *
     * @author jianlongwen
     * @date 2019/03/25
     */
    @RequestMapping(value = "/selectAccountHierarchy", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> selectAccountHierarchy(@JsonParam Account entity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<Account> accounts = accountService.selectAccountHierarchy(entity);
            result.put("data",accounts);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>经销审核:自动创建该经销商的三个资金账户（余额为0）， 然后新建一个外部用户，其用户名为手机号码。 密码为随机的6位数字。 然后需要给用户发送短信过去。</p>
     */
    @RequestMapping("dealerAudit")
    @ResponseBody
    public Map<String, Object> dealerAudit(@JsonParam Account entity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == entity.getId()) {
                throw new ServiceException("PUBLIC-007");
            }
            accountService.dealerAudit(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 修改状态
     */
    @RequestMapping(value = "/statusUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> statusUpdate(@JsonParam Account entity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            accountService.statusUpdate(entity);
            Account newEntry = getBasicService().queryById(entity);

            result.put("newRow", newEntry);
            result.put("success", true);

            /**
             * @author huanglongjian
             * @ 推送客户更新消息到cmq
             */
            CmqRes cmqRes = new CmqRes();
            List<CmqRes> cmqResList = cmqResService.queryAll(cmqRes);
            if (cmqResList.size() > 0) {
                try {
                    String type = newEntry.getAcctType();
                    String message1 = "";
                    //经销商
                    String dealer = "DEALER1";
                    //门店
                    String store = "STORE";
                    if (dealer.equals(type)) {
                        message1 = "AccountSyncl;{\"action\":\"Update\",\"objectId\":\"";
                        String message2 = "\"}";
                        String message = message1 + newEntry.getId() + message2;
                        String topicName = cmqResList.get(0).getQueueName();
                        MqUtil.sendCmqTopic(topicName, message);
                    } else if (store.equals(type)) {
                        message1 = "StoreSyncl;{\"action\":\"Update\",\"objectId\":\"";
                        String message2 = "\"}";
                        String message = message1 + newEntry.getId() + message2;
                        String topicName = cmqResList.get(0).getQueueName();
                        MqUtil.sendCmqTopic(topicName, message);
                    }
                } catch (Exception e) {
                    LCLogger.withException(e);
                }
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询所有类型为经销商的客户
     */
    @RequestMapping(value = "/queryDealerPage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryDealerPage(@JsonParam QueryParams qps, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        List<Account> list;
        try {

            Account t = BasicModel.transformClass(Account.class, qps);
            t.setAcctType("DEALER1");
            list = accountService.queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Account>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 新建拜访记录时选择客户
     */
    @RequestMapping(value = "/queryVisitAccountPage", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> queryVisitAccountPage(@JsonParam QueryParams qps, String visitPlanId,
                                                     HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        List<Account> list = new ArrayList<>();
        try {
            if (StringUtils.isBlank(visitPlanId)) {
                throw new ServiceException("ACCT-044");
            }
            qps.setAttr1(visitPlanId);
            Account t = BasicModel.transformClass(Account.class, qps);
            list = accountService.queryVisitAccountPage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", list);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>新建客户记录初始化方法，先生成ID并保存地址信息到数据库（不保存客户数据），再把ID返回前端</p>
     *
     * @param qps
     * @param session
     * @param request
     * @author yrf
     */
    @RequestMapping("newAccountInit")
    @ResponseBody
    public Map<String, Object> newDealerInit(@JsonParam QueryParams qps, HttpSession session, HttpServletRequest request) {
        LCLogger.info().withMessageKey("newAccountInit").withMessage("新建客户初始化...").flush();
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            Account record = accountService.preDefaultValue(new Account());
            //设置客户ID 和 客户地址ID，用于返回到前端。
            Long acctId = record.getId();
            record.setAcctCode(String.valueOf(acctId));
            //默认货币
            record.setCurrency("CNY");
            //默认客户状态
            record.setAcctStatus("Y");
            result.put("account", record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getLocalizedMessage());
        }
        return result;
    }

    /**
     * <p>设置新建客户记录的各项信息，包括联系人等，并且如果客户关联的地址省为空，</p>
     * <p>则把客户表单上的省市县地址设置到地址表的该项记录中</p>
     *
     * @param record
     * @author yrf
     */
    @RequestMapping("/dealerAdd")
    @ResponseBody
    public Map<String, Object> dealerAdd(@JsonParam Account record, HttpSession session, HttpServletRequest request) {
        LCLogger.info().withMessageKey("dealerAdd").withMessage("设置新建客户详细信息..." + record.getId()).flush();
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            //提取传入数据的联系人信息在数据库创建联系人记录
            if (record.getContactName() != null && !StringUtils.isNull(record.getContactName())) {
                if (null != record.getContactId()) {
                    accountService.copyToContactUpdate(record);
                } else {
                    record.setContactId(keyGenerateService.keyGenerate());
                    accountService.copyToContactInsert(record);
                }
            }
            //如果客户编码为空，以 row_id 做编码
            if (StringUtils.isNull(record.getAcctCode())) {
                record.setAcctCode(String.valueOf(record.getId()));
            }
            //accountService.copyToBsScopeInsert(record);//新建数据
            Account example = new Account();
            example.setId(record.getId());
            Account account = accountService.queryById(example);
            if (account != null) {
                //更新客户数据
                accountService.update(record);
            } else {
                //插入客户数据
                accountService.insert(record);
            }
            Long acctId = record.getId();

            result.put("success", true);
            result.put("acctId", acctId);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getLocalizedMessage());
        }
        return result;
    }

    /**
     * <p>返回客户新建页面</p>
     *
     * @param qps
     * @param session
     * @param request
     * @param response
     * @author yrf
     */
    @RequestMapping(value = "/backToAcctAdd")
    @ResponseBody
    public Map<String, Object> backToAcctAdd(@JsonParam QueryParams qps, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        Account account = new Account();
        String acctId = qps.getAttr2();
        try {
            qps.setId(Long.parseLong(acctId));
            qps.addFilter(new Filter("id", acctId));
            account.setId(Long.parseLong(acctId));
            account = accountService.queryById(account);
            if (account == null) {
                Account record = new Account();
                //设置客户ID 和 客户地址ID，用于返回到前端。
                Long newAcctId = keyGenerateService.keyGenerate();
                record.setId(newAcctId);
                CoreUser user = SecurityInterceptor.tempUser.get();
                Long sOrgid = user.getOrgId();
                String sOrgName = user.getOrgName();
                Long sPostnId = user.getPostnId();
                String sPostnName = user.getPostnName();
                record.setOrgId(sOrgid);
                record.setOrgName(sOrgName);
                record.setPostnId(sPostnId);
                record.setPostnName(sPostnName);
                record.setAcctCode(String.valueOf(newAcctId));
                account = record;
            }
            result.put("account", account);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getLocalizedMessage());
        }
        return result;
    }

    /**
     * <p>保存新建客户时第二步输入的客户区域等信息</p>
     *
     * @param account
     * @author yrf
     */
    @RequestMapping("updateNewAccount")
    @ResponseBody
    public Map<String, Object> newAccountUpdate(@JsonParam Account account, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == account.getId()) {
                throw new ServiceException("PUBLIC-007");
            }
            Account record = accountService.queryById(account);
            if (record != null) {
                record.setAccountBankName(account.getAccountBankName());
                record.setBillAddr(account.getBillAddr());
                record.setBillPhone(account.getBillPhone());
                //开票抬头
                record.setBillTitle(account.getBillTitle());
                record.setRegTaxNum(account.getRegTaxNum());
                record.setTaxpayerNumber(account.getTaxpayerNumber());
                record.setProvince(account.getProvince());
                record.setCity(account.getCity());
                record.setDistrict(account.getDistrict());
                record.setAddress(account.getAddress());
                record.setLongitude(account.getLongitude());
                record.setLatitude(account.getLatitude());
            } else {
                throw new ServiceException("ACCT-045");
            }
            accountService.update(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getLocalizedMessage());
        }
        return result;
    }

    /**
     * <p>修改主要联系人</p>
     *
     * @param account
     * @author heqiqian
     */
    @RequestMapping("mainContactUpdate")
    @ResponseBody
    public Map<String, Object> mainContactUpdate(@JsonParam Account account, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == account.getId()) {
                throw new Exception(exceptionIdInfo);
            }
            accountService.mainContactUpdate(account);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>修改主要资金账户</p>
     *
     * @param account
     * @author HuangLJ
     */
    @RequestMapping("mainBillUpdate")
    @ResponseBody
    public Map<String, Object> mainBillUpdate(@RequestBody Account account, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == account.getId()) {
                throw new Exception(exceptionIdInfo);
            }
            accountService.mainBillUpdate(account);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>修改主要合同</p>
     *
     * @param account
     * @author heqiqian
     */
    @RequestMapping("mainAgrUpdate")
    @ResponseBody
    public Map<String, Object> mainAgrUpdate(@JsonParam Account account, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == account.getId()) {
                throw new Exception(exceptionIdInfo);
            }
            accountService.mainAgrUpdate(account);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * <p>更新客户头信息</p>
     *
     * @param account
     * @author yrf
     */
    @RequestMapping("updateHeader")
    @ResponseBody
    public Map<String, Object> updateHeader(@RequestBody Account account, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == account.getId()) {
                result.put("success", false);
                result.put("result", exceptionIdInfo);
                return result;
            }
            accountService.acctHeaderUpdate(account);
            result.put("newRow", accountService.queryById(account));
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getLocalizedMessage());
        }
        return result;
    }

    /**
     * <p>更新客户详细信息</p>
     *
     * @param account
     * @author yrf
     */
    @RequestMapping("updateDetail")
    @ResponseBody
    public Map<String, Object> updateDetail(@RequestBody Account account, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == account.getId()) {
                result.put("success", false);
                result.put("result", exceptionIdInfo);
                return result;
            }
            accountService.acctDetailUpdate(account);
            ;
            result.put("newRow", accountService.queryById(account));
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getLocalizedMessage());
        }
        return result;
    }

    /**
     * 更新dms公司信息
     *
     * @param account
     * @return
     */
    @RequestMapping(value = "/updateDmsCompany")
    @ResponseBody
    public Map<String, Object> updateDmsCompany(@JsonParam Account account, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == account.getId()) {
                result.put("success", false);
                result.put("result", exceptionIdInfo);
                return result;
            }
            accountService.updateDmsCompany(account);

            Account newEntry = accountService.queryById(account);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 选择父对象时的picklist
     */
    @RequestMapping(value = "/parentPicklist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> parentPicklist(@JsonParam Account entity, @JsonParam QueryParams qps, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            Account account = (Account) BasicModel.transformClass(Account.class, qps);
            //安全性設置
            entity.preDealSecurity(request);
            List<Account> list = accountService.queryAccountListRemoveIdAndChildrenPage(entity);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(account, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Account>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 加载客户树
     */
    @RequestMapping(value = "/treelist/{initAcctId}")
    @ResponseBody
    public Account treelist(@PathVariable Long initAcctId, @JsonParam QueryParams qps, HttpSession session,
                            HttpServletRequest request, HttpServletResponse response) {
        Account root = new Account();
        try {
            root.setId(initAcctId);
            root = accountService.queryById(root);
            accountService.queryTreeByRoot(root);
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return root;
    }

    /**
     * 加载树
     */
    @RequestMapping(value = "/treelist")
    @ResponseBody
    public Map<String, Object> treelist(@JsonParam Account entity, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<Account> list = accountService.accountTreeList(entity);
            result.put("success", true);
            result.put("tree", true);
            //传根节点
            result.put("list", list.get(0));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("list", new Account());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询启信宝客户列表－分页 by客户名称
     *
     * @param session
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "/getQxbAccntListPaging")
    @ResponseBody
    public Map<String, Object> getQxbAccntListPaging(HttpSession session,
                                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        LCLogger.info().withMessageKey("getQxbAccntListPaging").withMessage("查询启信宝客户列表－分页 by客户名称.").flush();
        //客户名称
        String accntName = request.getParameter("accntName");
        //客户名称
        String searchValue = request.getParameter("searchValue");
        //跳过记录条数
        String page = request.getParameter("page");
        //跳过记录条数
        String skip = request.getParameter("skip");
        if (page != null && !"".equals(page)) {
            skip = String.valueOf((Integer.valueOf(page) - 1) * 20);
        }
        if (searchValue != null && !"".equals(searchValue)) {
            accntName = searchValue;
        }
        String queryResult = "";
        try {
            if (accntName == null || "".equals(accntName)) {
                queryResult = null;
                result.put("rows", new ArrayList<>());
                result.put("total", 0);
            } else {
                String param = "keyword=" + URLEncoder.encode(accntName, "UTF-8") + "&skip=" + skip + "&appkey=5babc31d44f4458a8dd051a39f63357f";
                LinkRedisClient jedis = null;
                try {
                    jedis = RedisUtil.getJedis();
                    String redisKey = "QXBP_" + param;
                    if (jedis.exists(redisKey)) {
                        queryResult = jedis.get(redisKey);
                        result.put("result", queryResult);
                    } else {
                        queryResult = HttpRequestUtil.sendGet("http://api.qixin007.com/APIService/enterprise/searchListPaging", param);
                        jedis.set(redisKey, queryResult);
                    }
                    try {
                        QxbResult qxbResult = JsonUtil.fromJsonStringToT(queryResult, QxbResult.class);
                        result.put("rows", qxbResult.getData().getItems());
                        result.put("total", qxbResult.getData().getTotal());
                    } catch (Exception e) {
                        LCLogger.withException(e);
                        ;
                        result.put("rows", new ArrayList<>());
                        result.put("total", 0);
                    }
                } finally {
                    RedisUtil.returnResource(jedis);
                }
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            ;
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询启信宝客户明细 by启信宝客户id
     *
     * @param session
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "/getQxbAccntItemById")
    @ResponseBody
    public Map<String, Object> getQxbAccntItemById(HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        //启信宝客户id
        String accntId = request.getParameter("accntId");
        LCLogger.info().withMessageKey("getQxbAccntItemById").withMessage("查询启信宝客户明细 by启信宝客户id." + accntId).flush();
        String queryResult = "";
        LinkRedisClient jedis = RedisUtil.getJedis();
        try {
            String param = "id=" + accntId + "&appkey=5babc31d44f4458a8dd051a39f63357f";
            String redisKey = "QXBO_" + param;
            if (jedis.exists(redisKey)) {
                queryResult = jedis.get(redisKey);
                result.put("result", queryResult);
            } else {
                queryResult = HttpRequestUtil.sendGet("http://api.qixin007.com/APIService/v2/enterprise/getDetailById", param);
                jedis.set(redisKey, queryResult);
                result.put("result", queryResult);
            }
            try {
                QxbDetailResult qxbResult = JsonUtil.fromJsonStringToT(queryResult, QxbDetailResult.class);
                result.put("result", qxbResult.getData());
            } catch (Exception e) {
                LCLogger.withException(e);
                result.put("success", false);
                result.put("result", null);
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }

        return result;
    }

    /**
     * 查询地区客户
     *
     * @param qps
     * @param order
     * @param session
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "/queryAccountOfDistrict", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAccountOfDistrict(@JsonParam QueryParams qps, @JsonParam Account order,
                                                      HttpSession session, HttpServletRequest request,
                                                      HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        Map<String, String> map = new HashMap<String, String>(16);
        //存放合并相同省后的数据
        List<Account> newList = new ArrayList<Account>(16);
        try {
            Account record = (Account) BasicModel.transformClass(Account.class, qps);
            record.setPageFlag(false);
            //按照总销量降序排序
//            record.setOrderByClause("total desc");
            List<Account> list = accountService.queryAccountOfDistrictPage(record);

            //合并省份一样的数据
            for (int i = 0; i < list.size(); i++) {
                //获取省份
                String key = list.get(i).getProvince();
                String old = map.get(key);
                if (old != null) {
                    map.put(key, old + "," + (i));
                } else {
                    map.put(key, "" + (i));
                }
            }
            Iterator<String> it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                String value = map.get(key);
                System.err.println(key + " 重复,行： " + value);
                String[] a = value.split(",");
                int sum = 0;
                for (int j = 0; j < a.length; j++) {
                    sum += list.get(Integer.valueOf(a[j])).getTotal();
                }
                Account newAccount = new Account();
                newAccount.setProvince(key);
                newAccount.setTotal(sum);
                //得到新的集合
                newList.add(newAccount);
            }
            //排序
            sortIntMethod(newList);
            //获取报表前端代码
            String html = accountService.getAccountReportHtml(newList);

            result.put("success", true);
            result.put("rows", newList);
            result.put("html", html);
            result.put("total", getCount((BasicModel) order, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }


    /***
     * 初始化客户
     *
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping(value = "/initializeAcct", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> initializeAcct(@JsonParam Account account, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            accountService.initializeAcct(account);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /***
     * 通过type 和独立源代码 查看指定值列表
     * @param type   类型
     * @param val    独立源代码
     * @throws Exception
     */
    private List<ListOfValue> queryLVByParams(String type, String val) throws Exception {
        ListOfValue entity = new ListOfValue();
//        entity.setOrderByClause(" seq asc ");
        entity.setActiveFlag("Y");
        entity.setPageFlag(false);
        //类型
        entity.setType(type);
        //独立源代码
        entity.setVal(val);
        return basicCommonService.queryByExamplePage(entity);
    }

    /**
     * 客户手机号的重复校验
     */
    @Override
    public void beforInsert(Account entity, HttpServletRequest request) throws Exception {
//      消费者数据同一个门店内只要填了手机号的，手机号不允许重复
        Account account = new Account();
        account.setAcctChannel(entity.getAcctChannel());
        account.setPageFlag(false);
        List<Account> list = accountService.queryByExamplePage(account);
        for (int i = 0; i < list.size(); i++) {
            //门店消费者标识
            String store = "Store";
            //来源是门店的校验MobilePhone1字段
            if (store.equals(entity.getAttr1())) {
                if (null != entity.getMobilePhone1() && entity.getMobilePhone1().equals(list.get(i).getMobilePhone1())) {
                    throw new ServiceException("PUBLIC-011");
                }
            } else {
                if (null != entity.getMobilePhone() && entity.getMobilePhone().equals(list.get(i).getMobilePhone())) {
                    throw new ServiceException("PUBLIC-011");
                }
            }
        }
    }

    /**
     * 获取虚拟消费者
     *
     * @param corpid
     * @return
     */
    @RequestMapping(value = "/virtualAccount")
    @ResponseBody
    public String virtualAccount(@RequestParam(value = "corpid") Long corpid,
                                 HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        return accountService.getVirtualAccount(corpid);
    }

    /**
     * check account
     *
     * @param record
     * @return
     */
    @RequestMapping(value = "/checkAccount")
    @ResponseBody
    public Map<String, Object> checkAccount(@RequestBody Account record,
                                            HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        // 门店+手机号码不存在时，先新建消费者记录，再将订单头上的客户Id赋值为该客户Id
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            Account account = accountService.checkAccount(record);
            result.put("success", true);
            result.put("result", account);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询客户标签组信息
     *
     * @author lizt
     * 2017年5月18日
     */
    @RequestMapping(value = "/queryQdAccntTagGroups", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryQdAccntTagGroups(@JsonParam TagGroup record, HttpSession session,
                                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<TagItem> list = accountService.queryQdAccntTagGroups(record);
            result.put("result", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查询客户标签信息
     *
     * @author lizt
     * 2017年5月18日
     */
    @RequestMapping(value = "/queryQdAccntTags", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryQdAccntTags(@JsonParam TagItem record, HttpSession session,
                                                HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<TagItem> list = accountService.queryQdAccntTags(record);
            result.put("result", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }


    /**
     * 通过ID查询客户标签信息
     *
     * @author lizt
     * 2017年3月27日
     * app 整合
     */
    @RequestMapping(value = "/queryTagsByAccntId", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryTagsById(TagItem record, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);

        try {
            List<TagItem> list = accountService.queryTagsById(record);
            result.put("result", list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 更新客户标签
     *
     * @author lizt
     * 2017年3月28日
     */
    @RequestMapping(value = "/updateTagList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateTagList(@RequestBody ListOfTags list, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);

        try {
            accountService.updateTagList(list);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 插入中间表
     *
     * @param entity 客户-识别顾客中间表对象
     * @author : LiQun
     * @date : 下午3:57 2018/5/7
     */
    @RequestMapping(value = "/accountPersonInsert")
    @ResponseBody
    public Map<String, Object> accountPersonInsert(@RequestBody AccountPerson entity) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            accountService.accountPersonInsert(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 生成客户二维码
     *
     * @author SiYe
     * 2017年8月8日
     */
    @RequestMapping(value = "/saveAccnt2CodeInfoNew", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveAccnt2CodeInfoNew(@RequestBody Account record, HttpSession session,
                                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);

        try {
            Account finAccnt = accountService.saveAccnt2CodeInfoNew(record);

            result.put("result", finAccnt);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 用户扫码后，返回用户微信基本信息
     *
     * @author ouyangzhenqiang
     * 2017年8月8日
     */
    @RequestMapping(value = "/queryHeadIconUrlAndMore", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryHeadIconUrlAndMore(@RequestBody Account record, HttpSession session,
                                                       HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);

        try {
            //查询客户头像url及更多信息
            Account finAccnt = accountService.queryUpdWxInfo(record);
            result.put("result", finAccnt);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 清空客户微信seq
     *
     * @author changwj
     * 2017年4月22日
     */
    @RequestMapping(value = "/emptyAccntSeq", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> emptyAccntSeq(@RequestBody Account record, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);

        try {
            //清空客户头像url及更多信息
            accountService.emptyAccntSeq(record);

            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }


    /**
     * 客户历程
     *
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryAccountExperience")
    public Map<String, Object> queryAccountExperience(@JsonParam Account entity, HttpSession session, HttpServletRequest request,
                                                      HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<AccountExperience> list = new ArrayList<AccountExperience>();
            // 客户id
            Long accountId = entity.getId();
            if (null != accountId) {
                // 获取接待列表
                Reception opty = new Reception();
                opty.setAccountId(accountId);
                List<Reception> optyList = receptionService.queryAll(opty);

                AccountExperience accountExperience = null;

                for (Reception reception : optyList) {
                    accountExperience = new AccountExperience();
                    accountExperience.setType("reception");
                    accountExperience.setRelatedId(reception.getId());
                    accountExperience.setGuideName(reception.getShoppingGuide());
                    accountExperience.setCreated(reception.getCreated());
                    accountExperience.setDealOrderStatus(reception.getDealOrderStatus());
                    accountExperience.setLeaveStoreReasonList(reception.getLeaveStoreReasonList());
                    list.add(accountExperience);
                }

                // 获取订单列表
                SaleOrder order = new SaleOrder();
                order.setAcctId(accountId);
                List<SaleOrder> orderList = saleOrderService.queryAll(order);

                for (SaleOrder saleOrder : orderList) {
                    accountExperience = new AccountExperience();
                    accountExperience.setType("order");
                    accountExperience.setRelatedId(saleOrder.getId());
                    accountExperience.setCreated(saleOrder.getOrderDate());
                    accountExperience.setOrderSource(saleOrder.getSourceFrom());
                    accountExperience.setSaleOrderItemList(saleOrder.getSaleOrderItemList());
                    accountExperience.setOrderStatus(saleOrder.getStatus());
                    accountExperience.setCreated(saleOrder.getCreated());
                    list.add(accountExperience);
                }

            }

            Collections.sort(list, new Comparator<AccountExperience>() {
                final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

                @Override
                public int compare(AccountExperience o1, AccountExperience o2) {
                    try {
                        Date date1 = sdf.parse(o1.getCreated());
                        return (sdf.parse(o2.getCreated()).compareTo(sdf.parse(o1.getCreated())));
                    } catch (ParseException e) {
                        LCLogger.withException(e);
                    }
                    return 0;
                }
            });

            result.put("rows", list);
            result.put("success", true);

        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 当传入经纬度时查询配置的附件门店的距离参数值
     * lujiang
     */
    @Override
    public void beforQueryExample(Account entity, HttpServletRequest request) throws Exception {
        CoreUser user = UserUtil.getUser();
        //当查询参数有经纬度的时候查询配置信息，如果没有配置信息抛出异常
        if (null != entity.getLongitude() && !("").equals(entity.getLongitude())) {
            //获取Mp对象
            Mp mp = new Mp();
            mp.setAppId(user.getMpAppId());
            mp.setPageFlag(false);
            List<Mp> mpList = mpService.queryByExamplePage(mp);
            if (mpList.size() > 0) {
                mp = mpList.get(0);
            } else {
                throw new ServiceException("ACCT-047");
            }
            if (null == mp || null == mp.getLimitDistance()) {
                throw new ServiceException("ACCT-048");
            }
            Double distance = Double.valueOf(mp.getLimitDistance()) * 1000;
        }
        super.beforQueryExample(entity, request);
    }


    /***
     * 客户签约提交审批
     * @author hhx
     * @param session
     * @param request
     * @param response
     *
     */
    @RequestMapping(value = "/accntSigningSubmit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> accntSigningSubmit(@RequestBody AccountApprovalInfo accountApprovalInfo, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        ObjectMapper mapper = new ObjectMapper();
        try {
            /*审批详情封装json字符串*/
            String approvalDetail = mapper.writeValueAsString(accountApprovalInfo);
            if (null == accountApprovalInfo.getAccntId()) {
                throw new RuntimeException(exceptionIdInfo);
            }
            Account account = new Account();
            account.setId(accountApprovalInfo.getAccntId());
            /*查找当前客户*/
            Account accntObj = accountService.queryById(account);
            if (accntObj == null) {
                throw new RuntimeException("客户不存在！");
            }
            accountService.accntSigningSubmit(accntObj, approvalDetail);
            Account newRow = accountService.queryById(account);
            result.put("success", true);
            result.put("newRow", newRow);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 导购助手-更新客户信息
     * 使用标准方法由于存在listOfTags字段,导致无法保存
     * 调用方法直接调用标准update
     *
     * @author : LiQun
     * @date : 2018/10/31
     */
    @RequestMapping(value = "/guideAccountUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> guideAccountUpdate(@RequestBody Account record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            accountService.update(record);
            record = accountService.queryById(record);
            result.put("success", true);
            result.put("result", record);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查询附件门店
     *
     * @param qps
     * @param entity
     * @param request
     * @return
     * @author lujiang
     */
    @RequestMapping(value = "/queryMpStoreByExamplePage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryMpStoreByExamplePage(@JsonParam QueryParams qps, @JsonParam Account entity,
                                                         HttpServletRequest request) {
        HashMap result = new HashMap(16);
        try {
            qps.preDealSecurity(request);
            Account temp = (Account) BasicModel.transformClass(entity, qps);
            this.beforQueryAllOrExample(temp, request);
            this.beforQueryExample(temp, request);
            temp.setTotalFlag(false);
            List<Account> list = accountService.queryMpStoreByExamplePage(temp);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("msg", e.getMessage());
        }

        return result;
    }

    /**
     * 微信加密数据解密
     *
     * @param record 查询数据
     * @return result 解密的数据
     * @throws Exception 异常信息
     * @author KuangRuifeng
     * @date 2018年11月29日
     */
    @RequestMapping(value = "/decryptWxData", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> decryptWxData(@RequestBody Account record) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
           // Map decryptData = accountService.decryptWxData(record);
            result.put("success", true);
          //  result.put("result", decryptData);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 小程序获取到手机号码后更新消费者
     *
     * @author KuangRuifeng
     * @date 2018/12/18
     */
    @RequestMapping(value = "/updMobilePhoneInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updMobilePhoneInfo(@RequestBody Account record, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (StringUtils.isBlank(record.getMobilePhone())) {
                throw new ServiceException("PUBLIC-009");
            }
            result = accountService.updMobilePhoneInfo(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查询访客信息
     *
     * @param entity
     * @return
     * @author 路江
     */
    @RequestMapping(value = "/queryAcctAndMember", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAcctAndMember(@RequestBody Account entity) {
        Map<String, Object> result = new HashMap<>(4);
        Account account;
        try {
            account = accountService.queryAcctAndMember(entity);
            result.put("rows", account);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 小程序联系客服用
     *
     * @author KuangRuifeng
     * @date 2019/1/12
     */
    @RequestMapping(value = "/contactMPService", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> contactMPService() {
        Map<String, Object> result = new HashMap<>(1);
        result.put("success", true);
        return result;
    }

    @RequestMapping(value = "/accnt/get", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> get(@RequestParam Long crmId, HttpServletRequest request,
                                   HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        Long acctId = crmId;
        try {
            ApiAccount accountExt = apiAccntService.getHeadAndItem(acctId);
            result.put("rows", accountExt);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/accnt/upsertHeadAndItem", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upsertHeadAndItem(@RequestBody ApiAccount model, HttpServletRequest request,
                                                 HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            ApiAccount accountExt = apiAccntService.upsertHeadAndItem(model);
            result.put("crmId", accountExt.getId());
            result.put("rows", accountExt);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    @RequestMapping(value = "/store/get", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> storeGet(@RequestParam Long crmId, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        Long acctId = crmId;
        try {
            ApiAccount accountExt = apiStoreService.getHeadAndItem(acctId);
            result.put("rows", accountExt);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/store/upsertHeadAndItem", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> storeUpsertHeadAndItem(@RequestBody ApiAccount model, HttpServletRequest request,
                                                      HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            ApiAccount accountExt = apiStoreService.upsertHeadAndItem(model);
            result.put("crmId", accountExt.getId());
            result.put("rows", accountExt);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 营销助手未登录状态下分享
     *
     * @author 旷锐锋
     * @date 2019/2/21
     */
    @RequestMapping({"/notLogin/queryById"})
    @ResponseBody
    public Map<String, Object> query(@JsonParam Account account, HttpSession session,
                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            // 未登录状态下，模拟登录，处理特殊逻辑
            result = super.queryById(account, session, request, response);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 判断当前小程序用户尝试登陆使用的手机号码是否合法
     *
     * @author KuangRuifeng
     * @date 2019/3/14
     */
    @RequestMapping(value = "/checkMPLoginPhone", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> checkMPLoginPhone(@RequestBody Account record, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (StringUtils.isBlank(record.getMobilePhone())) {
                throw new ServiceException("PUBLIC-009");
            }
            result = accountService.checkMPLoginPhone(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 通过openid查询消费者
     * @author Hlj
     * @date 2019年03月24日
     */
    @RequestMapping(value = "/queryConsumerByOpenId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryConsumerByOpenId(@RequestBody Account record) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            // 如果前端没有传入openid,则从user中取
            /*if (StringUtils.isBlank(record.getWxOwnOpenId())) {
                CoreUser user = UserUtil.getUser();
                record.setWxOwnOpenId(user.getOpenId());
            }*/
            Account account = accountService.queryConsumerByOpenId(record);
            result.put("success", true);
            result.put("result", account);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 重写查询客户接口
     * @author lujiang
     * @param qps
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @Override
    public Map<String, Object> queryByExamplePage(@JsonParam QueryParams qps,@JsonParam Account entity,
                                                  HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        HashMap result = new HashMap();
        try {
            qps.preDealSecurity(request);
            Account temp = (Account)BasicModel.transformClass(entity, qps);
            this.beforQueryAllOrExample(temp, request);
            this.beforQueryExample(temp, request);
            Boolean totalFlag = temp.getTotalFlag();
            temp.setTotalFlag(false);
            List<Account> list = this.getBasicService().queryByExamplePage(temp);
            result.put("success", true);
            result.put("rows", list);
            result.put("code", "200");
            this.pushCurrentDataCache(list, session.getId(), "base", false);
            if (totalFlag) {
                temp.setOnlyCountFlag(true);
                List<Account> accountList = this.getBasicService().queryByExamplePage(temp);
                Integer listTotal = 0;
                if (accountList.size() > 0) {
                    listTotal = accountList.get(0).getTotal();
                }
                result.put("total", listTotal);
            } else {
                result.put("total", getCount(temp, list.size()));
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据一个消费者信息，带出消费者对应所有会员(或电话号码)信息
     * @author wangdawei
     * Attr1标记是根据会员查还是根据电话号码查
     * @author Hlj
     * @date 2019年03月24日
     */
    @RequestMapping(value = "/queryAcctListById", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAcctListById(@RequestBody Account record) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            List<Account> accountList = accountService.queryAcctListById(record);
            result.put("success", true);
            result.put("result", accountList);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 会员-根据条件（会员id）获取客户数据
     *
     * @author lijie
     * @param record
     * @date   2019/8/09 12:00
     */
    @RequestMapping(value = "/queryByOtherExamplePage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryByOtherExamplePage(@RequestBody Account record, HttpSession session,
                                                       HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<Account> account = accountService.queryByExamplePage(record);
            result.put("success", true);
            result.put("result", account);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }



    /**
     * 微信更新消费者信息
     *
     * @author huanglongjian
     * @date 2019-10-22 14:17
     * @param
     * @return
     */
    @RequestMapping(value = "/wxUpdateAccount", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> wxUpdateAccount(@RequestBody Account record, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            Account account = accountService.wxUpdateAccount(record);
            result.put("success", true);
            result.put("result", account);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 消费者批量分配跟进
     *
     * @param entity -id 消费者主键
     * @param entity -postnId 被分配人职位ID
     * @return
     */

    @RequestMapping(value = "/accntDistribution", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> acctDistribution(@RequestBody Account entity) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            Long id = entity.getId();
            Long distributionId = entity.getPostnId();
            if (id == null || distributionId == null) {
                result.put("success", false);
                result.put("result", "传入参数有误");
                result.put("postnId", "");
                return result;
            }
            Account account = accountService.queryById(id);
            if (account == null) {
                result.put("success", false);
                result.put("result", "id[" + id + "]无渠道消费者");
                result.put("postnId", "");
                return result;
            }
            String unassigned = "Unassigned";
            Long postnId = account.getPostnId();
            String subAcctType = account.getSubAcctType();
            if (StringUtils.isBlank(subAcctType) || StringUtils.equals(unassigned, subAcctType)) {
                account.setPostnId(distributionId);
                account.setRow_status(BasicService.ROW_STATUS_UPDATE);
                account.setMobilePhone(account.getMobilePhone1());
                account.setAcctName(account.getAcctNameSecret());
                Account returnAccount = accountService.saveAccountToDmp(account);
                result.put("success", true);
                result.put("result", returnAccount);
                result.put("postnId", "");
                return result;
            } else {
                result.put("success", true);
                String fstName = account.getFstName();
                result.put("result", fstName);
                result.put("postnId", postnId);
                return result;
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("postnId", "");
        }
        return result;
    }

    /**
     * 客户冻结申请
     *
     * @author yangxiaolin
     * @date 2020/10/29
     */
    @RequestMapping(value = "/accountFreeze", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> accountFreeze(@JsonParam Account entity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            entity.setApprovalType("FreezeAccount");
            accountService.accountAudit(entity);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 客户解冻申请
     *
     * @author yangxiaolin
     * @date 2020/11/12
     */
    @RequestMapping(value = "/accountThaw", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> accountThaw(@JsonParam Account entity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            entity.setApprovalType("ThawAccount");
            accountService.accountAudit(entity);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 客户失效申请
     *
     * @author yangxiaolin
     * @date 2020/10/29
     */
    @RequestMapping(value = "/accountInactive", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> accountInactive(@JsonParam Account entity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            entity.setApprovalType("InactiveAccount");
            accountService.accountAudit(entity);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 客户冻结申请
     *
     * @author yangxiaolin
     * @date 2020/10/29
     */
    @RequestMapping(value = "/accountActive", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> accountActive(@JsonParam Account entity, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            entity.setApprovalType("ActiveAccount");
            accountService.accountAudit(entity);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
